<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use App\Model\PlayletEpisodesReplace;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class WxRelpaceTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    public static $replaceDramaMediaUrl = "https://api.weixin.qq.com/wxa/sec/vod/replacedramamedia";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'wxRelpace');
    }
    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始获取替换的');
        //获取需要获取任务的视频
        try {
            $replaceData = PlayletEpisodesReplace::query()->where(['status' => 2,'type' => 1])->get();
            $appletInfo = Applet::query()->where(['id' => 10000])->first();
            if($replaceData->isNotEmpty() && !empty($appletInfo)){

                $accessToken = $this->getWxAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
                foreach ($replaceData as $replaceDatum) {
                    //查询关联表中的小程序ID
                    $this->logger->info('查询该短剧，该集数:' . $replaceDatum->id);

                    $playletInfo = Playlet::query()->select(['id', 'name', 'drama_id', 'drama_status'])->where(['id' => $replaceDatum->playlet_id])->first();
                    $playletEpisodes = PlayletEpisodes::query()->select(['id','old_media_id','media_id'])->where(['id' => $replaceDatum->playlet_episodes_ids])->first();
                    $uplodata = $this->replaceUpolad($accessToken, $playletInfo->drama_id, $playletEpisodes->old_media_id, $playletEpisodes->media_id);
                    if(!empty($uplodata)){
                        $playletEpisodes->media_status = 3;
                        $playletEpisodes->save();

                        $replaceDatum->status = 3;
                        $replaceDatum->save();
                    }
                }
            }else{
                $this->logger->info('没有短剧审核数据');
            }
        }catch (\Exception $e){
            $this->logger->error('请求微信剧目过审后剧集Url|错误：' . $e->getLine() . '|' . $e->getMessage());
        }

        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时审核通过的短剧');
    }
    public function getWxAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
//        if(empty($accessToken)){
        $params         = [
            'grant_type' => 'client_credential',
            'appid'    => $app_id,
            'secret'   => $app_secret
        ];
        //获取token
        $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'GET');

        if (!empty($accessTokenInfo['access_token'])){
            $accessToken = $accessTokenInfo['access_token'];
            $redis->setex($key,7100,$accessToken);
        }else{
            $accessToken = "";
        }
//        }
        $this->logger->info('微信token为：'.$accessToken);
        return $accessToken;
    }
    public function replaceUpolad($accessToken,$drama_id,$old_media_id,$new_media_id){

        $params         = [
            "drama_id"    => $drama_id,
            "old_media_id" => $old_media_id,
            "new_media_id" => $new_media_id,
        ];

        $uploadUrl = self::$replaceDramaMediaUrl.'?access_token='.$accessToken;
        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$uploadUrl);
        //开始上传

        $uploadResult  = $this->request($params, $uploadUrl,'POST');
        if($uploadResult['errcode'] == 0){
            $this->logger->info('上传成功 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
            return $uploadResult;
        }else{
            $this->logger->error('上传失败 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
        }
        return false;
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
//        var_dump($requestParams);
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}